/* Turska UI library
 * Copyright 2003-2008 Jetro Lauha
 * All rights reserved.
 * Web: http://iki.fi/jetro/
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of EITHER:
 *   (1) The GNU Lesser General Public License as published by the Free
 *       Software Foundation; either version 2.1 of the License, or (at
 *       your option) any later version. The text of the GNU Lesser
 *       General Public License is included with this library in the
 *       file LICENSE-LGPL.txt.
 *   (2) The BSD-style license that is included with this library in
 *       the file LICENSE-BSD.txt.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files
 * LICENSE-LGPL.txt and LICENSE-BSD.txt for more details.
 *
 * $Id: UIComponent.cpp,v 1.2 2008/03/27 11:44:26 tonic Exp $
 * $Revision: 1.2 $
 */

#include "SDL.h"
#include "SDL_opengl.h"
#include "UI.h"


UIComponent::UIComponent(INT x, INT y, INT width, INT height) :
    mX(x), mY(y), mWidth(width), mHeight(height),
    mImageDrawMode(UIImage::NORMAL), mImageFlags(UIImage::COLOR | UIImage::CENTER),
    mIsPointerDown(false)
{
}


bool UIComponent::isInside(INT x, INT y)
{
    return x >= mX && y >= mY && x < mX + mWidth && y < mY + mHeight;
}


void UIComponent::addEventListener(UIEventListener *eventListener)
{
    mEventListeners.insert(eventListener);
}


void UIComponent::removeEventListener(UIEventListener *eventListener)
{
    EventListenerSet::iterator it = mEventListeners.find(eventListener);
    if (it != mEventListeners.end())
        mEventListeners.erase(it);
}


void UIComponent::removeAllEventListeners()
{
    mEventListeners.clear();
}


void UIComponent::onPointerDown(INT x, INT y)
{
    if (isInside(x, y))
    {
        mIsPointerDown = true;
        EventListenerSet::iterator it = mEventListeners.begin();
        EventListenerSet::iterator itend = mEventListeners.end();
        for (; it != itend; ++it)
            (*it)->onPointerDown(this, x, y);
    }
}


void UIComponent::onPointerUp(INT x, INT y)
{
    if (mIsPointerDown)
    {
        mIsPointerDown = false;
        EventListenerSet::iterator it = mEventListeners.begin();
        EventListenerSet::iterator itend = mEventListeners.end();
        for (; it != itend; ++it)
            (*it)->onPointerUp(this, x, y);
    }
}


void UIComponent::onPointerMove(INT x, INT y)
{
    if (mIsPointerDown)
    {
        EventListenerSet::iterator it = mEventListeners.begin();
        EventListenerSet::iterator itend = mEventListeners.end();
        for (; it != itend; ++it)
            (*it)->onPointerMove(this, x, y);
    }
}
